<?php

namespace App\Console\Commands\Shop;

use App\Exceptions\BaseException;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\User\Exceptions\UserException;
use App\Remote\TencentLbs\TencentLbsRemote;
use Doctrine\DBAL\Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Psr\SimpleCache\InvalidArgumentException;

class RefreshShopLbs extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'RefreshShopLbs';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷新门店经纬度信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     * @throws InvalidArgumentException
     */
    public function handle(): int
    {

        $errorShop      = [];
        $successShop    = [];
        $queryErrorShop = [];
        Shop::query()
            ->where("lng", "")
            ->where("lat", "")
            ->chunkById(100, function (Collection $shopCollection) use (&$errorShop, &$successShop, &$queryErrorShop) {
                $shopCollection->each(function (Shop $shopModel) use (&$errorShop, &$successShop, &$queryErrorShop) {
                    $this->info(vsprintf("正在执行 门店信息 【%d】【%s】", [$shopModel->id, $shopModel->name]));

                    if (empty($shopModel->address)) {
                        array_push($errorShop, [
                            "id"            => $shopModel->id,
                            "name"          => $shopModel->name,
                            "errMsg"        => null,
                            "addressPrefix" => $shopModel->addressPrefix,
                            "address"       => $shopModel->address,
                            "lng"           => $shopModel->lng,
                            "lat"           => $shopModel->lat,
                        ]);
                    } else {
                        try {
                            $locationDetail = TencentLbsRemote::addressAnalysis($shopModel->address);
                            ShopService::updateShopInfo(
                                ['id' => $shopModel->id],
                                [
                                    "lat" => $locationDetail["location"]["lat"],
                                    "lng" => $locationDetail["location"]["lng"],
                                ],
                                1,
                                false
                            );

                            array_push($successShop, [
                                "id"            => $shopModel->id,
                                "name"          => $shopModel->name,
                                "errMsg"        => null,
                                "addressPrefix" => $shopModel->addressPrefix,
                                "address"       => $shopModel->address,
                                "lng"           => $locationDetail["location"]["lng"],
                                "lat"           => $locationDetail["location"]["lat"],
                            ]);
                        } catch (\Exception $e) {
                            array_push($queryErrorShop, [
                                "id"            => $shopModel->id,
                                "name"          => $shopModel->name,
                                "errMsg"        => $e->getMessage(),
                                "addressPrefix" => $shopModel->addressPrefix,
                                "address"       => $shopModel->address,
                                "lng"           => $shopModel->lng,
                                "lat"           => $shopModel->lat,
                            ]);
                        }
                    }
                });
            });

        $this->getOutput()
             ->createTable()
             ->setHeaders(["门店ID", "门店名称", "错误信息", "详细地址前缀", "详细地址", "lng", "lat"])
             ->setRows(collect($successShop)->map(function ($v) {
                 return array_values($v);
             })->values()->toArray())
             ->render();
        $this->output->error(sprintf("成功门店 共 【 %d 】家", count($successShop)));

        $this->getOutput()
             ->createTable()
             ->setHeaders(["门店ID", "门店名称", "错误信息", "详细地址前缀", "详细地址", "lng", "lat"])
             ->setRows(collect($queryErrorShop)->map(function ($v) {
                 return array_values($v);
             })->values()->toArray())
             ->render();
        $this->output->error(sprintf("执行失败门店 共 【 %d 】家", count($queryErrorShop)));


        $this->getOutput()
             ->createTable()
             ->setHeaders(["门店ID", "门店名称", "错误信息", "详细地址前缀", "详细地址", "lng", "lat"])
             ->setRows(collect($errorShop)->map(function ($v) {
                 return array_values($v);
             })->values()->toArray())
             ->render();
        $this->output->error(sprintf("错误门店 共 【 {%d} 】家", count($errorShop)));

        return parent::SUCCESS;
    }
}
